package com.example.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.dao.AddressRepository;
import com.example.entity.Address;
import com.example.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 *
 */
@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    AddressRepository addressRepository;

    @Override
    public Address selectByAddress(String address) {

        return addressRepository.findByAddress(address);
    }

    @Override
    public Address selectById(Long id) {
        Optional<Address> address_Optional = addressRepository.findById(id);
        Address addressNode = address_Optional.get();
        return addressNode;
    }

    @Override
    public boolean deleteById(Long id) {
        Optional<Address> addressOptional = addressRepository.findById(id);
        Address addressNode = addressOptional.get();
        if (addressNode.getEventList() == null || addressNode.getEventList().size() == 0) {
            addressRepository.deleteById(id);
            return true;
        }
        return false;
    }

    @Override
    public JSONObject selectAll() {
        List<Address> addressNodeList = addressRepository.findAll();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", "success");
        jsonObject.put("data", addressNodeList);
        return jsonObject;
    }

    @Override
    public JSONObject update(Address address) {
        JSONObject jsonObject = new JSONObject();
        Optional<Address> addressOptional = addressRepository.findById(address.getId());
        Address addressNode = addressOptional.get();
        addressNode.setAddress(address.getAddress());
        addressNode = addressRepository.save(addressNode);
        jsonObject.put("msg", "success");
        jsonObject.put("data", addressNode);
        return jsonObject;
    }

    @Override
    public JSONObject insert(Address address) {
        JSONObject jsonObject = new JSONObject();
        Address address_temp =  addressRepository.findByAddress(address.getAddress());
        if (address_temp == null) {
            String uuid = UUID.randomUUID().toString();
            address.setLogicId(uuid);
            address.setHasParent(false);
            address.setHasChild(false);
            Address addressNode = addressRepository.save(address);
            jsonObject.put("msg", "success");
            jsonObject.put("data", addressNode);
            return jsonObject;
        }
        jsonObject.put("msg", "插入失败，因为还有关系关联");
        return jsonObject;
    }
}
